package com.sy.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * @Author yumax
 * @Date 2024 01 08 09 56
 **/
@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException, IOException {
        final ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new StringEncoder());
                    }
                })
                //1.连接到服务器
                // 异步非阻塞，main 发起了调用，真正执行connect是nio线程
                .connect(new InetSocketAddress("localhost", 8989));
        final long start = System.currentTimeMillis();
        //2.1 使用sync方法同步处理结果
        /*channelFuture.sync(); //阻塞住当前线程，直到nio线程连接建立完毕
        // 无阻塞向下执行获取channel
        final Channel sc = channelFuture.channel();
        log.debug("sc ..{}", sc);
        //2. 向服务器发送数据
        sc.writeAndFlush("test111");
        System.in.read();*/

        //2.2 使用addListener 方法异步处理结果
        channelFuture.addListener(new ChannelFutureListener() {
            //在nio线程连接建立好之后，会调用operationComplete
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.debug("耗时。。{}",System.currentTimeMillis() - start);
                final Channel sc = channelFuture.channel();
                log.debug("sc ..{}", sc);
                //2. 向服务器发送数据
                sc.writeAndFlush("test111");
                System.in.read();
            }
        });
    }
}
